package com.hutao.manage.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * Jaxb2工具类.
 */
public class JaxbUtil {
    /**
     * JavaBean转换成xml.
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj)  throws Exception{
        return convertToXml(obj, "UTF-8");
    }

    /**
     * JavaBean转换成xml.
     *
     * @param obj      bean实体
     * @param encoding 默认编码UTF-8
     * @return
     */
    private static String convertToXml(Object obj, String encoding) throws Exception {
        String result = null;
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
        return result;
    }

    /**
     * xml转成JavaBean.
     *
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) throws Exception {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        }catch (Exception e){
            throw new Exception();
        }
        return t;
    }
    
    public static void main(String[] args) throws Exception {
		Map map = new HashMap<>();
		map.put("mrId", "6591847");
		map.put("onlyId", "10975898");
		map.put("organizationId", "49557184-0");
		
		System.out.println(JsonUtil.objectToJson(map));
	}

}